from django.db import transaction
from rest_framework.decorators import action
from rest_framework import generics
from utils import response_error, response_ok
from utils.exceptions import CustomError
from utils.permission import IsMemberUser
from utils.custom_modelviewset import CustomModelViewSet
from .models import Store, Coupon, FocusStore
from .serializers import CouponSerializers, StoreCudSerializer, StoreDetailSerializer
from .filters import StoreFilter


class CouponViewSet(CustomModelViewSet):
    permission_classes = [IsMemberUser, ]
    serializer_class = CouponSerializers
    queryset = Coupon.objects.filter()

    def get_queryset(self):
        qs = super().get_queryset()  # 调用父类方法
        return qs.filter(merchant=self.request.user.member)

    def create(self, request, *args, **kwargs):
        try:
            coupon_ser = self.get_serializer(data=request.data)
            if coupon_ser.is_valid(raise_exception=True):
                with transaction.atomic():
                    coupon = coupon_ser.save(merchant=request.user.member)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                instance = self.get_object()
                if instance.merchant != request.user.member:
                    raise CustomError('未找到相应的优惠券')
                instance.delete = True
                instance.save()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()


class MineStoreView(generics.ListAPIView):
    permission_classes = [IsMemberUser, ]
    serializer_class = StoreDetailSerializer
    queryset = Store.objects.filter(delete=False)

    def get_queryset(self):
        qs = super().get_queryset()  # 调用父类方法
        return qs.filter(merchant=self.request.user.member)


class StoreViewSet(CustomModelViewSet):
    permission_classes = [IsMemberUser, ]
    serializer_class = StoreCudSerializer
    queryset = Store.objects.filter()

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                instance = self.get_object()
                instance.delete = True
                instance.save()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()

    @action(methods=['get'], detail=True)
    def focus(self, request, pk):
        try:
            store = Store.get_instance_by_id(pk)
            with transaction.atomic():
                instance, operate = FocusStore.objects.get_or_create(store=store, member=request.user.member)
            if operate:
                return response_ok('成功关注')
            else:
                instance.delete()
                return response_ok('成功取消关注')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
